﻿using KPIS.GERP.GAMS.APP.App_UI.Commons;
using KPIS.GERP.GAMS.DAL;
using KPIS.GERP.GAMS.MODEL;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;

namespace KPIS.GERP.GAMS.APP.App_UI.Forms
{
    public partial class ACM_AdjustTransection : System.Web.UI.Page
    {
        Main main = new Main();
        D_ACM_GENERAL_Ledger gl = new D_ACM_GENERAL_Ledger();
        D_ACM_MiscReport misc = new D_ACM_MiscReport();
        D_ACM_MAS_Account acc = new D_ACM_MAS_Account();
        D_BGM_MAS_Source source = new D_BGM_MAS_Source();
        MailMerge mailMerge = new MailMerge();

        protected enum Mode
        {
            AddNew,
            Edit,
            ViewAll,
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadDdlAccountSeq();
                LoadDdlBgmSourceSeq();
                lblTranSeq.Text = Request.QueryString["TranSeq"];

                if (lblTranSeq.Text.Length > 0)
                {
                    UpdateControl1(Mode.Edit);
                    LoadData();
                }
                else
                {
                    UpdateControl1(Mode.AddNew);
                    dpTranDate.SetValue(DateTime.Today);
                    lblTranSeq.Text = "";
                    txtBgmYear.Text = source.GetCurrentBgmYear();
                    txtTranName.Text = "";
                    txtRemarks.Text = "";
                }
            }
        }

        protected void LoadDdlAccountSeq()
        {
            ddlAccountSeq.DataSource = acc.GetListAccount();
            ddlAccountSeq.DataBind();

            if (ddlAccountSeq.Items.Count > 0)
            {
                ddlAccountSeq.SelectedIndex = 0;
            }
        }

        protected void LoadDdlBgmSourceSeq()
        {
            ddlBgmSourceSeq.DataSource = source.GetList();
            ddlBgmSourceSeq.DataBind();

            if (ddlBgmSourceSeq.Items.Count > 0)
            {
                ddlBgmSourceSeq.SelectedIndex = 0;
            }
        }

        protected void LoadData()
        {
            int nTranSeq = 0;
            
            if (!int.TryParse(lblTranSeq.Text, out nTranSeq))
            {
                return;
            }

            var model = gl.GetHeaderInfo(nTranSeq);

            if (model != null)
            {
                ddlBgmSourceSeq.SelectedValue = model.bgm_source_seq.ToString();
                txtBgmYear.Text = model.bgm_year.ToString();
                dpTranDate.SetValue(model.tran_date);
                lblTranCode.Text = model.tran_code;
                txtTranName.Text = model.tran_name;
                txtRemarks.Text = model.remark;

                lblFiscalPeriod.Text = model.fiscal_period;
                lblTranGrpSeq.Text = model.tran_grp_seq.ToString();
                lblRecordStatus.Text = model.record_status;

                LoadData2();

                cmdInsert1.Visible = lblRecordStatus.Text != "A";
                cmdUpdate1.Visible = lblRecordStatus.Text != "A";
                cmdDelete1.Visible = lblRecordStatus.Text != "A";
                cmdAddNew.Visible = lblRecordStatus.Text != "A";
            }
        }

        protected void LoadData2()
        {
            int nTranSeq = 0;

            if (!int.TryParse(lblTranSeq.Text, out nTranSeq))
            {
                return;
            }

            RadGridTransectionDtls.DataSource = gl.GetDtlsFullData(null, null, null, null, null, null, null, nTranSeq);
            RadGridTransectionDtls.DataBind();
        }

        protected bool CheckData1()
        {
            bool bOK = true;

            if (dpTranDate.GetDateValue() == null)
            {
                bOK = false;
            }
            else if (txtBgmYear.Text.Trim().Length == 0)
            {
                bOK = false;
            }
            else if (txtTranName.Text.Trim().Length == 0)
            {
                bOK = false;
            }
            else if (ddlBgmSourceSeq.SelectedValue.Length == 0)
            {
                bOK = false;
            }

            return bOK;
        }

        protected bool CheckData2()
        {
            bool bOK = true;

            if (txtAmount.Text.Trim().Length == 0)
            {
                bOK = false;
            }
            else if (ddlAccountSeq.SelectedValue.Length == 0)
            {
                bOK = false;
            }

            return bOK;
        }

        protected void UpdateControl1(Mode mode)
        {
            switch (mode)
            {
                case Mode.AddNew:
                    divTransectionDtls.Visible = false;
                    divEditTransectionDtls.Visible = false;
                    cmdInsert1.Visible = true;
                    cmdUpdate1.Visible = false;

                    lblModeName.Text = "เพิ่ม";
                    break;
                case Mode.Edit:
                    divTransectionDtls.Visible = true;
                    divEditTransectionDtls.Visible = false;
                    cmdInsert1.Visible = false;
                    cmdUpdate1.Visible = true;

                    lblModeName.Text = "แก้ไข";
                    break;
                case Mode.ViewAll:
                    divTransectionDtls.Visible = true;
                    divEditTransectionDtls.Visible = false;
                    cmdInsert1.Visible = false;
                    cmdUpdate1.Visible = true;

                    lblModeName.Text = "แสดงข้อมูล";
                    break;
            }
        }

        protected void UpdateControl2(Mode mode)
        {
            switch (mode)
            {
                case Mode.AddNew:
                    divTransectionDtls.Visible = false;
                    divEditTransectionDtls.Visible = true;
                    cmdInsert2.Visible = true;
                    cmdUpdate2.Visible = false;
                    cmdCancel2.Visible = true;

                    lblModeName2.Text = "เพิ่ม";
                    break;
                case Mode.Edit:
                    divTransectionDtls.Visible = false;
                    divEditTransectionDtls.Visible = true;
                    cmdInsert2.Visible = false;
                    cmdUpdate2.Visible = true;
                    cmdCancel2.Visible = true;

                    lblModeName2.Text = "แก้ไข";
                    break;
                case Mode.ViewAll:
                    divTransectionDtls.Visible = true;
                    divEditTransectionDtls.Visible = false;
                    cmdInsert2.Visible = false;
                    cmdUpdate2.Visible = false;
                    cmdCancel2.Visible = false;

                    lblModeName2.Text = "แสดงข้อมูล";
                    break;
            }
        }

        protected void cmdInsert1_Click(object sender, EventArgs e)
        {
            string strBgmSourceSeq = ddlBgmSourceSeq.SelectedValue;
            string strBgmYear = txtBgmYear.Text;
            DateTime? dtTranDate = dpTranDate.GetDateValue();
            string strTranCode = gl.GetNextTranCode(strBgmSourceSeq, strBgmYear, "A");
            string strTranName = txtTranName.Text;
            string strRemarks = txtRemarks.Text;

            if (!CheckData1())
            {
                main.MessageAlert(Page, "กรุณากรอกข้อมูลให้ครบถ้วน!!");
                return;
            }

            M_ACM_GENERAL_Ledger model = new M_ACM_GENERAL_Ledger();
            model.tran_code = strTranCode;
            model.tran_name = strTranName;
            model.bgm_source_seq = main.ConvertNullInt(strBgmSourceSeq);
            model.tran_date = dtTranDate;
            model.bgm_year = main.ConvertNullInt(strBgmYear);
            model.ref_no = null;
            model.ref_type = null;
            model.remark = strRemarks;
            model.tran_type = "A";
            model.work_area_seq = null;
            model.fiscal_period = main.GetFiscalPeriod(dtTranDate ?? DateTime.Today);
            model.tran_grp_seq = gl.GetNextTranGrpSeq();
            model.record_status = "W";
            model.created_by = Convert.ToInt32(Session["EmpSeq"].ToString());
            model.created_when = DateTime.Now;

            lblTranSeq.Text = gl.Insert_Transaction(model, true);

            if (string.IsNullOrEmpty(lblTranSeq.Text))
            {
                return;
            }

            LoadData();
            UpdateControl1(Mode.Edit);
        }

        protected void cmdUpdate1_Click(object sender, EventArgs e)
        {
            string strTranSeq = lblTranSeq.Text;
            string strBgmSourceSeq = ddlBgmSourceSeq.SelectedValue;
            string strBgmYear = txtBgmYear.Text;
            DateTime? dtTranDate = dpTranDate.GetDateValue();
            string strTranCode = lblTranCode.Text;
            string strTranName = txtTranName.Text;
            string strRemarks = txtRemarks.Text;

            if (!CheckData1())
            {
                main.MessageAlert(Page, "กรุณากรอกข้อมูลให้ครบถ้วน!!");
                return;
            }

            M_ACM_GENERAL_Ledger model = new M_ACM_GENERAL_Ledger();
            model.tran_seq = Convert.ToInt32(strTranSeq);
            model.tran_code = strTranCode;
            model.tran_name = strTranName;
            model.tran_date = dtTranDate;
            model.bgm_source_seq = main.ConvertNullInt(strBgmSourceSeq);
            model.bgm_year = main.ConvertNullInt(strBgmYear);
            model.ref_no = null;
            model.ref_type = null;
            model.remark = strRemarks;
            model.tran_type = "A";
            model.work_area_seq = null;
            model.fiscal_period = lblFiscalPeriod.Text;
            model.tran_grp_seq = main.ConvertNullInt(lblTranGrpSeq.Text);
            model.work_area_seq = null;
            model.record_status = lblRecordStatus.Text;
            model.updated_by = Convert.ToInt32(Session["EmpSeq"].ToString());
            model.updated_when = DateTime.Now;

            gl.Update_Transaction(model);

            LoadData();
            UpdateControl1(Mode.Edit);
        }

        protected void cmdCancel1_Click(object sender, EventArgs e)
        {

        }

        protected void cmdAddNew_Click(object sender, EventArgs e)
        {
            UpdateControl2(Mode.AddNew);

            lblTranDtlsSeq.Text = "";
            txtAmount.Text = "";
        }

        protected void cmdInsert2_Click(object sender, EventArgs e)
        {
            string strTranSeq = lblTranSeq.Text;
            string strAccountSeq = ddlAccountSeq.SelectedValue;
            string strDrOrCr = rdlDrOrCr.SelectedValue;
            string strAmount = txtAmount.Text;

            if (!CheckData2())
            {
                main.MessageAlert(Page, "กรุณากรอกข้อมูลให้ครบถ้วน!!");
                return;
            }

            M_ACM_GENERAL_Ledger model = new M_ACM_GENERAL_Ledger();
            model.tran_seq = Convert.ToInt32(strTranSeq);
            model.account_seq = main.ConvertNullInt(strAccountSeq);
            model.dr_or_cr = strDrOrCr;
            model.amount = main.ConvertNullDouble(strAmount);
            model.record_status = "W";
            model.created_by = Convert.ToInt32(Session["EmpSeq"].ToString());
            model.created_when = DateTime.Now;

            gl.Insert_DB_CR(model);

            LoadData2();
            UpdateControl2(Mode.ViewAll);
        }

        protected void cmdUpdate2_Click(object sender, EventArgs e)
        {
            string strTranDtlsSeq = lblTranDtlsSeq.Text;
            string strTranSeq = lblTranSeq.Text;
            string strAccountSeq = ddlAccountSeq.SelectedValue;
            string strDrOrCr = rdlDrOrCr.SelectedValue;
            string strAmount = txtAmount.Text;

            if (!CheckData2())
            {
                main.MessageAlert(Page, "กรุณากรอกข้อมูลให้ครบถ้วน!!");
                return;
            }

            M_ACM_GENERAL_Ledger model = new M_ACM_GENERAL_Ledger();
            model.tran_dtls_seq = Convert.ToInt32(strTranDtlsSeq);
            model.tran_seq = Convert.ToInt32(strTranSeq);
            model.account_seq = main.ConvertNullInt(strAccountSeq);
            model.dr_or_cr = strDrOrCr;
            model.amount = main.ConvertNullDouble(strAmount);
            model.record_status = "W";
            model.updated_by = Convert.ToInt32(Session["EmpSeq"].ToString());
            model.updated_when = DateTime.Now;

            gl.Update_DB_CR(model);

            LoadData2();
            UpdateControl2(Mode.ViewAll);
        }

        protected void cmdCancel2_Click(object sender, EventArgs e)
        {
            UpdateControl2(Mode.ViewAll);
        }

        protected void RadGridTransectionDtls_ItemCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {
            if (e.CommandName == "DataEdit")
            {
                GridDataItem item = (GridDataItem)e.Item;

                lblTranDtlsSeq.Text = main.WebString(item["tran_dtls_seq"].Text);
                ddlAccountSeq.SelectedValue = main.WebString(item["account_seq"].Text);
                rdlDrOrCr.SelectedValue = main.WebString(item["dr_or_cr"].Text);
                txtAmount.Text = rdlDrOrCr.SelectedValue == "Dr" ? main.WebString(item["debit_amount"].Text) : main.WebString(item["credit_amount"].Text);

                UpdateControl2(Mode.Edit);
            }
            else if (e.CommandName == "Delete")
            {
                GridDataItem item = (GridDataItem)e.Item;

                gl.Delete_DB_CR(Convert.ToInt32(main.WebString(item["tran_dtls_seq"].Text)), Convert.ToInt32(Session["EmpSeq"].ToString()), DateTime.Now);

                LoadData2();
            }
            else
            {
                LoadData2();
            }
        }

        protected void cmdDelete1_Click(object sender, EventArgs e)
        {
            string strTranSeq = lblTranSeq.Text;
            int nEmpSeq = Convert.ToInt32(Session["EmpSeq"].ToString());
            DateTime dt = DateTime.Now;

            M_ACM_GENERAL_Ledger model = gl.GetHeaderInfo(Convert.ToInt32(strTranSeq));
            model.record_status = "D";
            model.updated_by = nEmpSeq;
            model.updated_when = dt;
            gl.Update_Transaction(model);

            var model2 = gl.GetDtlsFullData(null, null, null, null, null, null, null, Convert.ToInt32(strTranSeq));

            foreach (var item in model2)
            {
                gl.Delete_DB_CR(item.tran_dtls_seq ?? 0, nEmpSeq, dt);
            }
        }

        protected void cmdPrint1_Click(object sender, EventArgs e)
        {
            string strTranSeq = lblTranSeq.Text;

            var tranInfo = gl.GetHeaderInfo(Convert.ToInt32(strTranSeq));
            var dtlsList = misc.ReportAdjust(strTranSeq);

            Dictionary<string, string> dic = new Dictionary<string,string>();
            dic.Add("L2", tranInfo.tran_code);
            dic.Add("L3", tranInfo.tran_date.HasValue ? tranInfo.tran_date.Value.ToLongDateString() : "");
            dic.Add("C5", tranInfo.tran_name);

            Dictionary<string, DataTable> dic2 = new Dictionary<string, DataTable>();
            dic2.Add("A8", dtlsList);

            mailMerge.MergeExcel(Response, Server.MapPath("~/Reports/Templates/Adjust.xlsx"), string.Format("Adjust-{0}", DateTime.Now.ToString("yyyyMMddHHmmssffff")), dic2, dic);
        }
    }
}